﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using GoodDotNet.Core.Model;
using GoodDotNet.WebAdmin.AuthHelper.Policys;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;

namespace GoodDotNet.WebAdmin.HttpContextUser
{
    public class AspNetUser : IUser
    {
        private readonly IHttpContextAccessor _accessor;
        private Audiences _audiences;

        /// <summary>
        /// 用户id
        /// </summary>
        public int Id { get; set; }

        /// <summary>
        /// 用户名称
        /// </summary>
        public string Name { get; set; }

        public AspNetUser(IHttpContextAccessor accessor, IOptions<Audiences> audiences)
        {
            _accessor = accessor;
            _audiences = audiences.Value;

            var token = _accessor.HttpContext.Request.Headers[_audiences.Token].ToString().Replace("Bearer ", "");
            var result = new JwtToken(_audiences).GetPrincipal(token);
            if (result != null)
            {
                Name = result.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name)?.Value;
                Id = Convert.ToInt32(result.Claims.FirstOrDefault(c => c.Type == "id")?.Value);
              }
        }
      
    }
}
